import streamlit as st
import sys
import os
import subprocess
sys.path.append("..")
import utills
from moviepy.editor import VideoFileClip
import re
from streamlit_card import card
import time
from annotated_text import annotated_text
import extra_streamlit_components as stx

# Set page configuration to hide the sidebar on load
st.set_page_config(layout="wide")
upload_folder = "./upload/video_input/"
landmarks_folder = "./landmarks"
visualize_folder = "./visualize"

if "uploadState" not in st.session_state:
    st.session_state.uploadState = "Unupload"
if "VideoState" not in st.session_state:
    st.session_state.VideoState = "none"
def convert_avi_to_mp4(folder_path):
    # 获取文件夹下所有文件
    files = os.listdir(folder_path)

    # 循环遍历文件
    for file in files:
        if file.endswith('.avi'):
            avi_path = os.path.join(folder_path, file)
            mp4_path = os.path.join(folder_path, file[:-4] + '.mp4') # 修改文件后缀为.mp4
            clip = VideoFileClip(avi_path)
            clip.write_videofile(mp4_path)

def exec_threading(function):
    exec_anlze = utills.ThreadExecutor(function)
    #开始线程
    exec_anlze.start()

    #线程等待
    exec_anlze.join()


def clear_folder(folder_path):
    # 获取文件夹中的所有文件和子文件夹
    files = os.listdir(folder_path)
    if not files:  # 如果文件夹为空
        return "文件夹内无文件"
    for file in files:
        # 构建文件/文件夹的完整路径
        file_path = os.path.join(folder_path, file)
        # 如果是文件，则删除
        if os.path.isfile(file_path):
            os.remove(file_path)
        # 如果是文件夹，则递归清空
        elif os.path.isdir(file_path):
            clear_folder(file_path)


with st.sidebar: 
    st.header("人脸篡改视频检测模块")
    # annotated_text(
    #     "基于人脸识别+时空特征的双流递归神经网络检测模型",
    
        
    
        


    # )
    st.markdown("_基于人脸识别+时空特征的双流递归神经网络检测模型_")
    annotated_text(
        ("real ","真","#42CF52")
    )
    annotated_text(
        ("doubt ","存疑","#F7E62F")
    )
    annotated_text(
        ("fake ","假","#F0275E")
    )
    annotated_text(
        ("伪造指数","该值越高我们越趋向于目标为假","#23ACF0")
    )

headCol = st.columns([1,1,1])
with headCol[1]:
     image_url = ""
     stx.bouncing_image(image_source=image_url, animate=False, animation_time=1500, height=200, width=250)
Buttoncontainer = st.container()

with Buttoncontainer:
    ButtonCol = st.columns([3,2,2])

    with ButtonCol[1]:
        st.write("")
        mybutton = st.button("清除残余文件")
        if mybutton:
            folder_path = "./upload/video_input"  # 替换为您要清空的文件夹路径
            #清空视频输入
            clear_folder(folder_path)
            #清空landmark
            clear_folder(landmarks_folder)
            #清空visualize
            clear_folder(visualize_folder)
            st.session_state.uploadState = "Unupload"
            clear_folder("./upload")

            images_folder_path = "./upload/images"  # 替换为您要清空的文件夹路径
            #清空page2图片输入
            clear_folder(images_folder_path)
            st.session_state.Page3uploadState = "Unupload"
            st.success("文件夹已清空！")
            st.session_state.VideoState = "none"
            st.session_state.VideoState = "none"
            st.session_state.mainState = "Unupload"
            st.session_state.WelcomeState = "Unupload"
            if os.path.exists("/home/xinan-works/complex_layout_example.pdf"):
                os.remove("/home/xinan-works/complex_layout_example.pdf")
                print(f"文件 pdf 删除成功")
            else:
                print("文件不存在，无法删除")


mainCol = st.columns([6,1])
with mainCol[0]:
    uploaded_file = st.file_uploader("")
    uploaded_filename = None  # 初始化变量用于存储上传文件的文件名

    # 如果有文件被上传
    if uploaded_file is not None:
        st.session_state.uploadState = "uploaded"
        # 将文件保存到指定路径
        file_path = os.path.join(upload_folder, uploaded_file.name)
        with open(file_path, "wb") as f:
            f.write(uploaded_file.getbuffer())
        
        # 存储上传文件的文件名
        uploaded_filename = uploaded_file.name
emoji_col = st.columns([4,4,4])
if st.session_state.uploadState == "Unupload":
    with emoji_col[1]:
        st.header("☝️🙄先上传视频哦")
if st.session_state.uploadState == "uploaded":
    with emoji_col[1]:
        st.header("🫵😎文件上传成功")







if st.session_state.uploadState == "uploaded":
    ProgressContainer =  st.empty()
    with ProgressContainer:
        bar=st.progress(0)
        #进度条
        
        for i in range(80):
            bar.progress(i+1)
            time.sleep(0.1)

    ThidCol = st.columns([6,1])
    with ThidCol[0]:
        exec_threading(utills.extract_landmarks())
        landmarks_files = os.listdir(landmarks_folder)
        if not landmarks_files:
            st.write("请先确保landmarks结果存在")
        #classify 
        results = utills.classify()
        text = results[0]

            # 使用正则表达式截取label和分数部分
        pattern = r'Prediction label: (\w+); Scores:(\d+\.\d+)'
        match = re.search(pattern, text)

        if match:
    
            score_str = match.group(2)
            score = float(score_str)
            correct = 20*score/7
            if correct >=0.6:
                st.session_state.VideoState = "fake"
                label = "fake"
            elif 0.4<correct<=0.6:
                st.session_state.VideoState = "doubt"
                label = "doubt"
            else:
                st.session_state.VideoState = "real"
                label = "real"
    
        #将文件转换成为可以被前端展示出来的mp4文件
        convert_avi_to_mp4("./visualize")
        ProgressContainer.empty()

 


    if st.session_state.VideoState == "fake":
        res = card(
            title="Fake !!!!!!😡",
            text="看起来这是一个伪造的对象",
            image="https://www.zfuhao.com/upload/image/2022/1642085446656393.jpg",
            styles={
                "card": {
                    "width": "450px",
                    "height": "300px",
                    "border-radius": "60px",
                    "box-shadow": "0 0 10px rgba(234,0,0,0.5)",
                    "background-color": "rgba(234, 0, 0, 0)"
                },
                "text": {
                    "font-family": "serif",
                },
                "filter": {
                    "background-color": "rgba(234, 0, 0, 0)"  # <- make the image not dimmed anymore
                }
            }
        )
    if st.session_state.VideoState == "real":
        res = card(
            title="Wow",
            text="🙂好像没有伪造痕迹哦",
            image="https://gd-hbimg.huaban.com/51da9549e3377a5287671a92aace8f7b534546e2d30-i7ZEfU_fw658",
            styles={
                "card": {
                    "width": "450px",
                    "height": "300px",
                    "border-radius": "60px",
                    "box-shadow": "0 0 10px rgba(234,0,0,0.5)",
                    "background-color": "rgba(234, 0, 0, 0)"
                },
                "text": {
                    "font-family": "serif",
                },
                "filter": {
                    "background-color": "rgba(234, 0, 0, 0)"  # <- make the image not dimmed anymore
                }
            }
        )
    if st.session_state.VideoState == "doubt":
        res = card(
    title="Ooops ？！🤔",
    text="有点可疑，但是又有点不可疑",
    image="https://ts1.cn.mm.bing.net/th/id/R-C.d641eb2b1984277fe7eb301deaab2b8d?rik=awiunEDr9AFqTw&riu=http%3a%2f%2fpics.sc.chinaz.com%2ffiles%2fpic%2fpic9%2f201703%2fzzpic1687.jpg&ehk=1sYFoEaGFyJithPejoU7Br7is6GVRRA7ta9kIkTeizU%3d&risl=&pid=ImgRaw&r=0&sres=1&sresct=1",
    styles={
        "card": {
            "width": "450px",
            "height": "300px",
            "border-radius": "60px",
            "box-shadow": "0 0 10px rgba(234,0,0,0.5)",
            "background-color": "rgba(234, 0, 0, 0)"
        },
        "text": {
            "font-family": "serif",
        },
        "filter": {
            "background-color": "rgba(234, 0, 0, 0)"  # <- make the image not dimmed anymore
        }
    }
)


    BaseCol = st.columns(1)
    with BaseCol[0]:
        with st.container(border=True):
            VideoCol = st.columns(2)
            with VideoCol[0]:
                with st.container(border=True):
                    utills.show_video(f"./upload/video_input/{uploaded_file.name}")

            with VideoCol[1]:
                with st.container(border=True):
                    utills.show_video(f"./visualize/{uploaded_file.name}_track.mp4")

            TextCol = st.columns(1)
            with TextCol[0]:
                with st.container(border=True):
                    st.header(f"文件名：{uploaded_file.name}")
    ThridCol = st.columns(1)
    with ThridCol[0]:
        with st.container(border=True):
            ResCol = st.columns([1,1])
            # with ResCol[1]:
            #     st.header(f"伪造指数:")
            with ResCol[0]:
                html_text = f"<div style='background-color:#23ACF0; padding-top:5px; border-radius:5px; font-size:26px; padding-right:20px;'><span style='padding-left:10px;'>{correct}</span></div>"
                st.write("")
                st.markdown(html_text, unsafe_allow_html=True)
            with ResCol[1]:
                if st.session_state.VideoState == "real":
                    html_text = f"<div style='background-color:#42CF52; padding-top:5px; border-radius:5px; font-size:26px; padding-right:20px;'><span style='padding-left:10px;'>鉴定是real</span></div>"
                    st.write("")
                    st.markdown(html_text, unsafe_allow_html=True)
                if st.session_state.VideoState == "doubt":
                    html_text = f"<div style='background-color:#F7E62F; padding-top:5px; border-radius:5px; font-size:26px; padding-right:20px;'><span style='padding-left:10px;'>鉴定是doubt</span></div>"
                    st.write("")
                    st.markdown(html_text, unsafe_allow_html=True)
                if st.session_state.VideoState == "fake":
                    html_text = f"<div style='background-color:#F0275E; padding-top:5px; border-radius:5px; font-size:26px; padding-right:20px;'><span style='padding-left:10px;'>鉴定是fake</span></div>"
                    st.write("")
                    st.markdown(html_text, unsafe_allow_html=True)







            # DisCol = st.columns(2)
            # with st.container(border=True):
            #     with DisCol[0]:
            #         with st.container(border=True):
            #             if st.session_state.VideoState == "real":
            #                 annotated_text(
            #                     ("real ","真","#42CF52")
            #                 )
            #             if st.session_state.VideoState == "doubt":
            #                 annotated_text(
            #                         ("doubt","存疑","#F7E62F")
            #                 )
                            
            #             if st.session_state.VideoState == "fake":
            #                 annotated_text(
            #                     ("fake ","假","#F0275E")
            #                 )

            #     correct = abs(0.5-score)*2
            #     with DisCol[1]:
            #          with st.container(border=True):
            #             annotated_text(
            #             (f"{correct}","伪造指数","#23ACF0")
            #                         )




